package top.soulblack.purchasesale.service;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Service;
import top.soulblack.purchasesale.controller.wechat.config.WechatEditConfig;
import top.soulblack.purchasesale.mapper.*;
import top.soulblack.purchasesale.model.*;

import java.lang.String;
import java.util.*;

@Service
@Slf4j
public class WechatEditService {
    @Autowired
    private WechatTableEditMapper wechatTableEditMapper;
    @Autowired
    private WechatTableColumnMapper wechatTableColumnMapper;
    @Autowired
    private WechatAccessService wechatAccessService;
    @Autowired
    private WechatTableClassifyMapper wechatTableClassifyMapper;

    //操作结果重新查询实体,table_id索引
    private Map<Integer, List<Map<String, Object>>> result;

    public WechatEditConfig getEditConfig(Integer editId) {
        //数据表配置索引,table_id索引
        Map<Integer, WechatEditLink> tableConfig = new LinkedHashMap<>();
        //预填充数据索引,table_id索引,target_id索引source_id
        Map<Integer, Map<Integer, Integer>> paddingData = new LinkedHashMap<>();
        //操作设计的表,table_id索引
        Map<Integer, WechatTableClassify> tables = new LinkedHashMap<>();
        Map<Integer, List<WechatTableColumn>> columns = new LinkedHashMap<>();
        //table_id为索引，关联表缓冲用
        Map<Integer, WechatTableClassify> tableCache = new LinkedHashMap<Integer, WechatTableClassify>();
        WechatTableEdit wechatTableEdit = wechatTableEditMapper.selectByPrimaryKey(editId);
        for (WechatEditLink editLink : wechatTableEdit.getEditLinks()) {
            WechatTableClassify table = wechatTableClassifyMapper.selectByPrimaryKey(editLink.getTableId());
            columns.put(table.getId(), wechatTableColumnMapper.selectByPid(table.getId()));
            tables.put(table.getId(), table);
            tableConfig.put(table.getId(), editLink);
            if (StringUtils.isNotBlank(editLink.getPaddingId()) && StringUtils.isNotBlank(editLink.getPaddingTargetId())) {
                String sources[] = editLink.getPaddingId().split(",");
                String targets[] = editLink.getPaddingTargetId().split(",");
                if (sources.length == targets.length) {
                    if (!paddingData.containsKey(table.getId()))
                        paddingData.put(table.getId(), new LinkedHashMap<>());
                    for (int i = 0; i < sources.length; i++) {
                        paddingData.get(table.getId()).put(Integer.parseInt(targets[i]), Integer.parseInt(sources[i]));
                    }
                }
            }
        }
        //关联输入项缓存
        Map<Integer, List<Map<String, Object>>> cache = new LinkedHashMap<Integer, List<Map<String, Object>>>();
        Map<Integer, WechatTableColumn> linkColCache = new LinkedHashMap<Integer, WechatTableColumn>();

        for (Integer key : columns.keySet())
            for (WechatTableColumn column : columns.get(key)) {
                if (column.getLinkId() != null) {
                    //如果缓存了关联节点
                    if (linkColCache.containsKey(column.getLinkId())) {
                        column.setLinkColumn(linkColCache.get(column.getLinkId()));
                    } else {
                        WechatTableColumn linkColumn = wechatTableColumnMapper.selectByPrimaryKey(column.getLinkId());
                        linkColCache.put(column.getLinkId(), linkColumn);
                        column.setLinkColumn(linkColumn);
                    }
                    //如果缓存了数据
                    if (cache.containsKey(column.getLinkId())) {
                        column.setData(cache.get(column.getLinkId()));
                    } else {
                        WechatTableClassify childTable;
                        if (tableCache.containsKey(column.getLinkColumn().getPid())) {
                            childTable = tableCache.get(column.getLinkColumn().getPid());
                        } else {
                            childTable = wechatTableClassifyMapper.selectByPrimaryKey(column.getLinkColumn().getPid());
                            tableCache.put(childTable.getId(), childTable);
                        }
                        List<Map<String, Object>> data = wechatAccessService.selectList(childTable,
                                Arrays.asList(childTable.getIndex(), column.getLinkColumn().getName()), new ArrayList<String>(), new ArrayList<String>());
                        column.setData(data);
                        cache.put(column.getLinkId(), data);
                    }
                }
            }
        return new WechatEditConfig(wechatTableEdit, tableConfig, paddingData, tables, columns, tableCache);
    }

    /**
     * @return boolean
     * @Author li
     * @Description 保存编辑结果
     * @Date 14:52 2019/8/30
     * @Param [editId, data]
     **/
    public void saveEdit(Integer editId, Map<String, String[]> data) {
        Map<String, String[]> input = new LinkedHashMap<>();
        for (String key : data.keySet()) {
            String[] values = data.get(key);
            input.put(key, values);
        }
        WechatEditConfig wechatEditConfig = this.getEditConfig(editId);
        //cloumn_id索引项
        Map<Integer, WechatTableColumn> wechatTableColumns = new LinkedHashMap<>();
        for (Integer tableKey : wechatEditConfig.columns.keySet()) {
            for (WechatTableColumn column : wechatEditConfig.columns.get(tableKey)) {
                wechatTableColumns.put(column.getId(), column);
            }
        }

        //如果主键名不是id
        if (input.containsKey("id") & wechatTableColumns.get(wechatEditConfig.page.getColIndex()).getName() != "id") {
            input.put(wechatTableColumns.get(wechatEditConfig.page.getColIndex()).getName(), input.get("id"));
        }

        Map<Integer, Map<String, Object>> result = new LinkedHashMap<>();
        int tableLength = wechatEditConfig.tableConfig.size();
        List<Integer> updatedTables = new ArrayList<>();
        for (int temp = 0; temp < tableLength; temp++) {
            if (updatedTables.size() == tableLength) {
                break;
            }
            for (Integer tableKey : wechatEditConfig.tableConfig.keySet()) {
                if (updatedTables.contains(tableKey)) {
                    continue;
                }
                boolean readyUpdate = true;
                //判断所需参数是否足够
                if (wechatEditConfig.paddingData.containsKey(tableKey)) {
                    if (wechatEditConfig.paddingData.get(tableKey).size() != 0)
                        for (Integer tarKey : wechatEditConfig.paddingData.get(tableKey).keySet()) {
                            if (!result.containsKey(wechatTableColumns.get(wechatEditConfig.paddingData.get(tableKey).get(tarKey)).getPid())) {
                                readyUpdate = false;
                            }
                        }
                }
                //已包含所需数据
                if (readyUpdate) {
                    List<String> columns = new ArrayList<>();
                    List<Map<String, Object>> upadteData = new ArrayList<>();
                    for (WechatTableColumn column : wechatEditConfig.columns.get(tableKey)) {
                        columns.add(column.getName());
                    }
                    //获取多输入的数量
                    Integer size = 0;
                    for (String column : columns) {
                        if (input.containsKey(column))
                            size = input.get(column).length > size ? input.get(column).length : size;
                    }
                    //生成updatedata
                    for (int i = 0; i < size; i++) {
                        Map<String, Object> interoData = new LinkedHashMap<>();
                        for (WechatTableColumn column : wechatEditConfig.columns.get(tableKey)) {
                            if (input.containsKey(column.getName())) {
                                if (input.get(column.getName())[i]!=null) {
                                    interoData.put(column.getName(), input.get(column.getName())[i]);
                                }
                            } else if (wechatEditConfig.paddingData.size() != 0) {
                                if (wechatEditConfig.paddingData.containsKey(tableKey))
                                    if (wechatEditConfig.paddingData.get(tableKey).containsKey(column.getId()))
                                        interoData.put(column.getName(), result.get(wechatTableColumns.get(wechatEditConfig.paddingData.get(column.getPid()).get(column.getId())).getPid()).get(wechatTableColumns.get(wechatEditConfig.paddingData.get(column.getPid()).get(column.getId())).getName()));
                            }
                        }
                        upadteData.add(interoData);
                    }
                    //入库
                    for (Map<String, Object> oneData : upadteData) {
                        List<String> updateColumns = new ArrayList<>();
                        for (WechatTableColumn col : wechatEditConfig.columns.get(tableKey)) {
                            updateColumns.add(col.getName());
                        }
                        if (oneData.containsKey(wechatEditConfig.tables.get(tableKey).getIndex())) {
                            int res = wechatAccessService.updateByPrimaryKey(wechatEditConfig.tables.get(tableKey), Integer.parseInt((String) oneData.get(wechatEditConfig.tables.get(tableKey).getIndex())), updateColumns, oneData);
                            if (res > 0) {
                                result.put(tableKey, wechatAccessService.selectByPrimaryKey(wechatEditConfig.tables.get(tableKey), (Integer) oneData.get("id")));
                            }
                        } else {
                            int res = wechatAccessService.insert(wechatEditConfig.tables.get(tableKey), oneData);
                            if (res > 0) {
                                result.put(tableKey, wechatAccessService.selectByPrimaryKey(wechatEditConfig.tables.get(tableKey), (Integer) oneData.get("id")));
                            }
                        }
                    }
                    updatedTables.add(tableKey);
                }
            }
        }
    }
}



